package com.qf.openapi.web.master.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.openapi.web.master.dao.UserDao;
import com.qf.openapi.web.master.entity.User;
import com.qf.openapi.web.master.service.UserService;
import com.qf.openapi.web.master.utils.Constants;
import com.qf.openapi.web.master.utils.FileAppender;
import com.qf.openapi.web.master.vo.ResultVo;
import com.qf.openapi.web.master.vo.TableVo;
import com.qf.openapi.web.master.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo addUser(UserVo userVo) {
        if (!userVo.equals("") && userVo != null) {
            User user = UserVoToUser(userVo);
            userDao.addUser(user);
            return new ResultVo("添加成功", Constants.SUCCESS);
        }
        return new ResultVo("添加失败", Constants.DEFAULT);

    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public User login(String username, String password) {
        String s = DigestUtil.md5Hex(password);
        User user = userDao.login(username, s);
        log.info("UserServiceImpl:username={},password={},user={}", username, password, user);
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo updateUser(UserVo userVo) {
        if (!userVo.equals("") && userVo != null) {
            User user = UserVoToUser(userVo);
            Integer i = userDao.updateUser(user);
            if (i != 0) {
                return new ResultVo("修改成功", Constants.SUCCESS);
            }
            return new ResultVo("修改失败", Constants.DEFAULT);
        }
        return new ResultVo("修改失败", Constants.DEFAULT);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public TableVo<User> getUsersByContditions(Integer page, Integer limit, UserVo userVo) {
        PageHelper.startPage(page, limit);
        List<User> list =  userDao.getUsersByContditions(userVo);
        PageInfo<User> info = new PageInfo<>();
        Integer integer = userDao.selectCount();
        info.setList(list);
        return  TableVo.ok(integer,list);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public ResultVo export() throws Exception {
        List<User> users =  userDao.selectall();
        List<String> collect = users.stream().map(user -> user.toString()).collect(Collectors.toList());
        new FileAppender<User>().appendListtoFile(collect);
        return new ResultVo("导出成功",1,FileAppender.getFileName());
    }

    private User UserVoToUser(UserVo userVo) {
        String pas = userVo.getPassword();
        String s = DigestUtil.md5Hex(pas);
        String username = userVo.getUsername();
        String pwd = userDao.selectPasswordById(userVo.getId());
        if (pwd != null &&pwd.equals(userVo.getPassword())) {
            final User user = new User();
            BeanUtils.copyProperties(userVo, user);
            user.setPassword(pas);
            user.setUsername(username);
            return user;
        } else {
            final User user = new User();
            BeanUtils.copyProperties(userVo, user);
            user.setPassword(s);
            user.setUsername(username);
            return user;
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVo checkUserName(String username) {
        User user = userDao.getUserByName(username);
        if (user != null) {
            return new ResultVo("用户名存在", Constants.DEFAULT);
        } else {
            return new ResultVo("用户名不存在", Constants.SUCCESS);
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public TableVo<User> getAllUserByPage(Integer page, Integer limit) {
        Integer i = userDao.selectCount();
        final int beginRow = (page - 1) * limit;
        List<User> users = userDao.getUserByPage(beginRow, limit);
        TableVo<User> vo = new TableVo<>();
        vo.setCode(0);
        vo.setMsg("success");
        vo.setData(users);
        vo.setCount(i);
        return vo;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public TableVo<User> getAllUserByPageHelper(Integer page, Integer limit) {

        PageHelper.startPage(page, limit);

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo deleteUserById(Integer[] ids) {
        Integer i = userDao.deleteUserById(ids);
        if (i != 0) {
            return new ResultVo("删除成功", Constants.SUCCESS);
        } else {
            return new ResultVo("删除失败", Constants.DEFAULT);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo insert(UserVo userVo, String path) throws IOException {
        //文件处理

        //1. 生成一个唯一的文件名 ： 唯一前缀 + 原始文件名+
        MultipartFile mail = userVo.getFile1();
        final String prefix = UUID.randomUUID().toString();
        final String originalFilename = mail.getOriginalFilename();
        final String finalName = prefix + originalFilename;
        final String filePath = path + File.separator + finalName;
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        mail.transferTo(file1);
        final User t_user = new User();
        BeanUtils.copyProperties(userVo, t_user);
        t_user.setPhotopath(finalName);
        t_user.setUsername(userVo.getUsername());
        String s = DigestUtil.md5Hex(userVo.getPassword());
        t_user.setPassword(s);
        userDao.insert(t_user);
        return null;
    }
}
